import { companyDepartmentGet } from '@/api/departments'

const state = {
  departmentList: [],
  initList: []
}
const getters = {
  IntegrateDepartment(getters, state, str = '') {
    return state.departmentList.filter((item) => {
      if (item.pid === str) {
        item.children = getters.IntegrateData(
          getters,
          state.departmentList,
          item.id
        )
        return item
      }
      3
    })
  }
}
const mutations = {
  mutDepartment(state, value) {
    state.departmentList = value
  },
  mutInit(state, value) {
    state.initList = value
  }
}
const actions = {
  async actDepartment({ state, commit }) {
    if (state.departmentList.length === 0) {
      const res = await companyDepartmentGet()
      console.log(res.data.depts)
      const data = IntegrateData(res.data.depts)
      commit('mutDepartment', data)
      commit('mutInit', [...res.data.depts])
      // getters.IntegrateDepartment()
    }
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}

const IntegrateData = function(arr, str = '') {
  return arr.filter((item) => {
    if (item.pid === str) {
      item.children = IntegrateData(arr, item.id)
      return item
    }
  })
}
